/**
 * 我的页面
 * /pages/user/index
 * @author WeChat Mini Program Team
 * @since 2025-08-14
 */

const Router = require('../../utils/router')
const Storage = require('../../utils/storage')
const Logger = require('../../utils/logger')
const Track = require('../../utils/track')

// 引入相关服务
const { CommunityService, TeacherService, BuddyService, SwapService, UserService } = require('../../services/index')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: '个人中心',
    loading: false,
    userInfo: null,
    menuList: [
      { id: 'profile', icon: '/images/user.png', title: '个人资料', url: '/pages/user/profile/index' },
      { id: 'my-courses', icon: '/images/common.png', title: '我的课程', url: '/pages/teacher/my-courses/list' },
      { id: 'my-learning', icon: '/images/common.png', title: '我的学习', url: '/pages/teacher/my-learning/index' },
      { id: 'orders', icon: '/images/common.png', title: '我的订单', url: '/pages/teacher/orders/list' },
      { id: 'settings', icon: '/images/common.png', title: '设置', url: '/pages/user/settings/index' }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    Logger.info('Page loaded: /pages/user/index')
    Track.trackPageView('/pages/user/index')
    this.loadUserInfo()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时的逻辑
  },

  /**
   * 加载详情数据
   */
  async loadUserInfo() {
    this.setData({ loading: true })
    try {
      if (UserService && UserService.getUserProfile) {
        const res = await UserService.getUserProfile()
        if (res && res.data) {
          this.setData({ userInfo: res.data })
        }
      }
    } catch (e) {
      Logger.error('加载用户信息失败', e)
      wx.showToast({ title: '加载失败', icon: 'error' })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 操作按钮点击
   */
  onMenuTap(e) {
    const url = e.currentTarget.dataset.url
    if (url) {
      Router.navigateTo(url)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onPullDownRefresh() {
    this.loadUserInfo().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  onShareAppMessage() {
    Track.trackShare('miniprogram', this.data.title)
    return {
      title: this.data.title,
      path: '/pages/user/index',
      imageUrl: '/images/share-default.jpg'
    }
  },
})